<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">新增角色</el-button>
    </div>

    <el-table
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column label="角色编号" prop="id" sortable="custom" align="center" width="100">
        <template slot-scope="scope">
          <span>Role102</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" width="100px" align="center">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">仓库管理员</span>
        </template>
      </el-table-column>
      <el-table-column label="角色类型" width="100px" align="center">
        <template slot-scope="scope">
          <span>业务办理类</span>
        </template>
      </el-table-column>
      <el-table-column label="角色访问权限" align="center" width="270">
        <template slot-scope="scope">
          <span v-if="scope.row.pageviews">单商户,多商户,单部门,多部门,整个机构</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="角色职能描述" align="center" width="240">
        <template slot-scope="scope">
          <span v-if="scope.row.pageviews">负责管理仓库所有商品库存变化</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" width="160px" align="center">
        <template slot-scope="scope">
          <span>2019-02-26 08:31:47</span>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" align="center" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.pageviews">正常
          </span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" align="center" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-popover placement="right" width="550" height="250" trigger="click">
            <template>
              <el-transfer
                :filter-method="filterMethod"
                :titles="['未选员工', '已选员工']"
                v-model="value2"
                :data="data2"
                filterable
                filter-placeholder="请输入员工名称"/>
            </template>
            <el-button slot="reference" type="info" size="mini" align="center">用户</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色编号" prop="title">
          <el-input name="code" value="Role102"/>
        </el-form-item>
        <el-form-item label="角色名称" prop="title">
          <el-input name="name" value="仓库管理员"/>
        </el-form-item>
        <el-form-item label="角色类型" prop="title">
          <el-select placeholder="请选择" value="1">
            <el-option label="信息维护类" value="1"/>
            <el-option label="业务办理类" value="2"/>
            <el-option label="统计查询类" value="3"/>
            <el-option label="其他未分类" value="9"/>
          </el-select>
        </el-form-item>
        <el-form-item label="角色访问权限" prop="title">
          <el-input name="LinkAddress" value="单商户,多商户,单部门,多部门,整个机构"/>
        </el-form-item>
        <el-form-item label="使用状态" prop="title">
          <el-select placeholder="请选择" value="1">
            <el-option label="正常" value="1"/>
            <el-option label="停用" value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期" prop="timestamp">
          <el-date-picker value="2019-02-20 08:31:47" type="datetime" placeholder="Please pick a date"/>
        </el-form-item>
        <el-form-item label="角色职能描述" prop="title">
          <el-input :autosize="{ minRows: 2, maxRows: 4}" value="负责管理仓库所有商品库存变化" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

const statusNameMap = {
  published: '开通',
  draft: '暂存',
  deleted: '删除'
}

const generateData2 = _ => {
  const data = []
  const cities = ['张三金', '李国民', '赵贴金', '李金明', '高近品', '严燕丽', '周成鸣']
  const pinyin = ['801103', '801105', '801106', '801107', '801108', '801109', '801110']
  cities.forEach((city, index) => {
    data.push({
      label: city,
      key: index,
      pinyin: pinyin[index]
    })
  })
  return data
}

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    statusNameFilter(status) {
      return statusNameMap[status]
    }
  },
  data() {
    return {
      data2: generateData2(),
      value2: [],
      checkedCities1: ['张三', '王五'],
      cities: ['张三', '李四', '王五', '严六', '燕七', '朱八', '高九', '赵十'],
      statusMap: {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      },
      gridData: [{
        userID: '801105',
        userName: '李晓明',
        userOrg: '市场部',
        userState: '正常'
      }, {
        userID: '801105',
        userName: '李晓明',
        userOrg: '市场部',
        userState: '正常'
      }, {
        userID: '801105',
        userName: '李晓明',
        userOrg: '市场部',
        userState: '正常'
      }, {
        userID: '801105',
        userName: '李晓明',
        userOrg: '市场部',
        userState: '正常'
      }, {
        userID: '801105',
        userName: '李晓明',
        userOrg: '市场部',
        userState: '正常'
      }],
      statusArr: [
        {
          key: 'published',
          value: '开通'
        },
        {
          key: 'draft',
          value: '暂存'
        },
        {
          key: 'deleted',
          value: '删除'
        }
      ],
      statusNameMap,
      tableKey: 0,
      list: [],
      totalList: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        status: undefined,
        sort: '+id'
      },
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  filterMethod(query, item) {
    return item.pinyin.indexOf(query) > -1
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      if (this.totalList.length == 0) {
        this.total = 200
        for (let i = 0; i < this.total; i++) {
          this.totalList.push({
            id: i + 1,
            author: '鲁迅',
            title: '标题' + (i + 1),
            timestamp: 1548680325680,
            status: 'published',
            pageviews: 1,
            reviewer: '主编'
          })
        }
      } else {
        this.totalList = this.totalList.filter(e => {
          let flag = true
          if (this.listQuery.status) {
            flag = e.status == this.listQuery.status
          }
          if (this.listQuery.title) {
            flag = e.title == this.listQuery.title
          }
          return flag
        })
      }
      this.list = this.totalList.slice((this.listQuery.page - 1) * this.listQuery.limit, this.listQuery.page * this.listQuery.limit)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['popover4'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    test() {
      alert('1')
      import('@/views/table/complexTable201')
      alert('')
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
